# core/apps.py
import os
import sys
import logging
from django.apps import AppConfig


# 获取当前模块的日志记录器
logger: logging.Logger = logging.getLogger(__name__)


class CoreConfig(AppConfig):
    name: str = "core"

    def ready(self) -> None:
        """应用就绪时执行初始化"""
        # 判断当前是否通过 runserver 启动
        is_runserver: bool = "runserver" in sys.argv
        # 检查是否是主进程(避免 runserver 重载时重复初始化)
        is_main_process: bool = bool(os.environ.get("RUN_MAIN"))
        # 判断当前是否通过 uvicorn 启动
        is_uvicorn: bool = "main.py" in " ".join(sys.argv)
        # 仅在实际运行的主进程中初始化
        if (is_runserver and is_main_process) or is_uvicorn:
            print("初始化成功")
            try:
                # 导入日程系统初始化函数
                from utils.task_util import scheduler_manager

                # 执行日程系统初始化
                scheduler_manager.initialize()
            except ImportError as e:
                logger.warning(f"❌ 无法导入日程工具: {e}")
            except Exception as e:
                logger.error(f"❌ 日程系统初始化失败: {e}")
